import React from 'react';
import styles from './index.less';
import {
  Modal,
  DatePicker,
  Space,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Row,
  Col,
  Skeleton,
  Spin,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;
import { TEdit, UserEditObject } from './TEdit';
import request from '@/http';
import qs from 'qs';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [currentEditObject, setCurrentEditObject] =
    React.useState<UserEditObject>({
      isModalVisible: false,
    });
  const [formObject] = Form.useForm();

  const [searchValue, setSearchValue] = React.useState('');
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 10,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '200', '500'],
    showQuickJumper: true,
  });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    // const result: any = await request.get('/admin/queryAllTeacherInfo?pageInfo.pageIndex=' + (pageValue - 1) + '&pageInfo.pageSize=' + sizeValue, {
    const ds = {
      ...userParams,
      current: pageValue,
      size: pageSize,
    };
    const result: any = await request.post(
      '/api/admin/teacherInfoManagement/getTeacherInfoByPage',
      qs.stringify(ds),
    );
    console.log(pageValue);
    console.log(pageSize);
    console.log('教师信息：', result);

    if (result && result.code == '200') {
      const data: any = result.data.records.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        name: user.name,
        userNo: user.userNo,
        idNo: user.idNo,
        sex: user.sex,
        mobileNo: user.mobileNo,
        position: user.position,
        delFlag: user.delFlag,
      }));

      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.records, //总条数 分页               *******************
      };

      setPagination(newPageObject);
      setDataSource(data);

      setLoadingState({ loading: false });
    }
    if (result.code == 201) {
      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.records, //总条数 分页               *******************
      };
      setPagination(newPageObject);
      setDataSource(result.data);
    }
  };

  //搜索
  const searchOnClick = async () => {
    setLoadingState({ loading: true });
    const data = await formObject.validateFields();
    var dataStr = '';
    var ds = {
      ...data,
    };
    console.log(data);
    for (var n in ds) {
      if (dataStr != '') dataStr += '&';
      dataStr += encodeURIComponent(n) + '=' + encodeURIComponent(ds[n]);
    }

    await loadDataSource(data, 1, pagination.pageSize);
  };

  //生命周期函数
  React.useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize).finally();
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  async function userEditOnClose() {
    await loadDataSource(
      formObject.getFieldsValue(),
      pagination.current,
      pagination.pageSize,
    );
  }

  //切换教师状态按钮
  const disableOnClick = async (user: any) => {
    console.log(user.delFlag);
    if (user.delFlag == 1) user.delFlag = 0;
    else user.delFlag = 1;
    console.log(user.delFlag);

    const result: any = await request.get(
      '/api/admin/teacherInfoManagement/disableOrEnable?id=' +
        user.id +
        '&delFlag=' +
        user.delFlag,
    );
    console.log('改变状态后：', result);
    if (result.code == '200') {
      setTimeout(() => {
        message.success('操作成功！');
      }, 500);

      await loadDataSource(
        formObject.getFieldsValue(),
        pagination.current,
        pagination.pageSize,
      );
    }
  };

  //重置按钮
  const resetOnClick = () => {
    formObject.resetFields();
  };

  /*  const [state, setState] = React.useState({
      selectedRowId: [], // Check here to configure the default column
      loading: false,
    });
    const { loading, selectedRowId } = state;
    const rowSelection = {
      selectedRowId,
      onChange: onSelectChange,
    };
    function onSelectChange(selectedRowId: any) {
      console.log('selectedRowKeys changed: ', selectedRowId);
      setState({ loading: false, selectedRowId });
    }*/

  //切换教师 状态  对话框
  function showDeleteConfirm(val: any) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      title: '温馨提示',
      content: '是否更改教师状态？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        disableOnClick(val).then((r) => {
          console.log('ok');
        });
      },
    });
  }

  /*const hasSelected = selectedRowId.length > 0;
  const flag = hasSelected;

  function showDeleteAllConfirm(val: any) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      title: '温馨提示',
      content: '是否删除所有选中教师？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        if (flag) {
          deleteOnClick(val).then((r) => {
            console.log('需要删除的id:', val);
          });
        } else {
          message.error('请选择需要删除的教师！');
        }
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }

  const deleteOnClick = async (user: any) => {
    console.log(222);
    var arr = [].concat(selectedRowId);
    var newArr = arr.map((item, index) => {
      // @ts-ignore
      return Number(item.slice(5));
    });
    console.log(newArr);

    const result: any = await request.get('/admin/deleteStudentById?');
    if (result.success) {
      message.success('操作成功！');
      await loadDataSource(
        formObject.getFieldsValue(),
        pagination.current,
        pagination.pageSize,
      );
    }
  };
  */
  const layout = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 },
  };

  return (
    <div className="pageMain">
      <div className="pageContent">
        <Row
          className="search"
          style={{
            height: '140px',
            minWidth: 1200,
            maxWidth: 1300,
          }}
        >
          <div className={styles.searchForm}>
            <Form layout="inline" form={formObject}>
              <Col span={8}>
                <Form.Item label="老师姓名" name="name">
                  <Input className="teacherInput" placeholder="模糊查询" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="工号" name="userNo" initialValue="">
                  <Input className="teacherInput" placeholder="请输入..." />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="身份证号" name="idNo" initialValue="">
                  <Input className="teacherInput" placeholder="请输入..." />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="手&nbsp;&nbsp;机&nbsp;&nbsp;号"
                  name="mobileNo"
                  initialValue=""
                >
                  <Input
                    className="teacherInput"
                    placeholder="请输入..."
                    value={searchValue || ''}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="状态" name="delFlag" initialValue="">
                  <Select style={{ width: 270 }} value={searchValue || ''}>
                    <Option value="">请选择...</Option>
                    <Option value="1">有效</Option>
                    <Option value="0">无效</Option>
                  </Select>
                </Form.Item>
              </Col>

              <Form.Item>
                {/*<Button className='searchBtn' type="primary" onClick={searchOnClick}>查询</Button>*/}
                <Button type="primary" onClick={searchOnClick}>
                  查询
                </Button>
              </Form.Item>
              <Button style={{ marginLeft: -20 }} onClick={resetOnClick}>
                重置
              </Button>
            </Form>
          </div>
        </Row>

        <div className={styles.mainTable}>
          <Button
            style={{ margin: '0 10px 10px 0' }}
            type="primary"
            onClick={() => {
              setCurrentEditObject({
                isModalVisible: true,
              });
            }}
          >
            新增
          </Button>
          {/*   <Button
            style={{ margin: '0 10px 10px 0' }}
            onClick={() => {
              showDeleteAllConfirm({
                selectedRowId,
              });
            }}
          >
            批量删除
          </Button>*/}
          <Spin tip="Loading..." spinning={loadingState.loading}>
            <Table
              // rowSelection={rowSelection}
              className="ptTable"
              columns={[
                {
                  title: '教师姓名',
                  dataIndex: 'name',
                  key: 'name',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '工号',
                  dataIndex: 'userNo',
                  key: 'userNo',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '身份证号',
                  dataIndex: 'idNo',
                  key: 'idNo',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '性别',
                  dataIndex: 'sex',
                  key: 'sex',
                  width: 50,
                  align: 'center',
                },
                {
                  title: '手机号',
                  dataIndex: 'mobileNo',
                  key: 'mobileNo',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '职位',
                  dataIndex: 'position',
                  key: 'position',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '状态',
                  dataIndex: 'delFlag',
                  key: 'delFlag',
                  width: 75,
                  align: 'center',
                  render: (delFlag: any) => (delFlag == '1' ? '有效' : '无效'),
                },

                {
                  title: '操作',
                  key: 'action',
                  align: 'center',
                  width: 75,
                  render: (row: any) => (
                    <>
                      <Button
                        type="link"
                        onClick={() => {
                          setCurrentEditObject({
                            ...row,
                            isModalVisible: true,
                          });
                        }}
                        style={{ padding: '4px 8px' }}
                      >
                        编辑
                      </Button>
                      {/*<Button type="link" onClick={() => {*/}
                      {/*  disableOnClick(row).finally();*/}
                      {/*}} style={{padding:'4px 8px'}}>*/}
                      {/*  停用*/}
                      {/*</Button>*/}
                      <Space>
                        <Button
                          onClick={() => {
                            showDeleteConfirm({
                              ...row,
                            });
                          }}
                          type="link"
                        >
                          {row.delFlag == 1 ? '停用' : '启用'}
                        </Button>
                      </Space>
                    </>
                  ),
                },
              ]}
              onChange={pageOnChange}
              dataSource={dataSource}
              pagination={pagination}
              tableLayout="fixed"
              bordered
            />
          </Spin>
        </div>
        <TEdit editObject={currentEditObject} onClose={userEditOnClose} />
      </div>
    </div>
  );
};
